var portaluserno = getCookie('portaluserno')
var configInfo = InitialParameter("/Config.json");
var modelApi = getBaseplatformPort()
var dashboardData = []
$(document).ready(function () {
    if (!portaluserno) {
        location.href = "/"
    } else {

        getData()
        echartsLineRealTime()
        eventFun()
        textFun()
        saveFun()
    }
})

function eventFun() {
    $('.topTab div').click(function (event) {
        $(this).addClass('activeTitle').siblings('div').removeClass('activeTitle')
        let textName = event.target.innerHTML
        if (textName == '近一周') {
            getData(1)
        } else if (textName == '近两周') {
            getData(2)
        } else if (textName == '近一个月') {
            getData(3)
        }
    })
}

function sendAjax(url, type, data) {
    $.ajaxSettings.async = false;
    var results;
    $.ajax({
        type: type,
        dataType: "json",
        url: url,
        data: data,
        success: function (data) {
            results = data;
        },
        error: function (error) {
            results = error;
        }
    });
    return results;
}

function getData(name) {
    let type = 1

    if (name) {
        type = name
    }
    var results = sendAjax(modelApi + "resource/serviceMonitoring", "POST", {
        type
    });
    if (results.code == 200) {
        dashboardData = results.data
        $('#platformUptime').html(dashboardData.runTimes + '天')
        $('#platformAccess').html(dashboardData.platformVisits + '次')
        $('#registeredUsers').html(dashboardData.registerUserCounts + '人')
        $('#registrationAgencies').html(dashboardData.deptCounts + '个')
        $('#totalNumber').html(dashboardData.resourceCounts + '次')
        $('#abnormalService').html(dashboardData.exceptionResource + '个')
        textFun()
    } else {
        layer.msg(results.msg, {
            icon: 2,
            shade: [0.5, '#000', true],
            time: 500
        });
    }
    return dashboardData
}

function getTimes() {
    var arr = []
    var timeI = 15
    var date = new Date();
    var year = date.getFullYear(); //月份从0~11，所以加一
    var dateArr = [date.getMonth() + 1, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()];
    for (var i = 0; i < dateArr.length; i++) {
        if (dateArr[i] >= 1 && dateArr[i] <= 9) {
            dateArr[i] = "0" + dateArr[i];
        }
    }
    // var strDate = year+'-'+dateArr[0]+'-'+dateArr[1]+' '+dateArr[2]+':'+dateArr[3]+':'+dateArr[4];
    for (let i = 0; i < 14; i++) {
        if (i == 0) {
            arr.push((dateArr[1]))
        }
        arr.push((dateArr[1] -= 1))
    }
    return {
        year: dateArr[0],
        data: arr
    }
}

function echartsLineRealTime() {
    let x = getTimes() 
    let resourceBts = dashboardData.resourceBts 
    let arr = ['数据服务个数','专题服务个数','通用服务个数']
    let arr1 = []
    let index = -1 
    let timer = [1,2,3,4,5,6,7,8,9,10,11,12]
    resourceBts.map(item => { 
        index += 1
        arr1.push({
            value:item,
            name: arr[index]
        })
    })  

    var myChart = echarts.init(document.getElementById('platformAccessEchart'), 'walden');
    var myChart1 = echarts.init(document.getElementById('onlineUsers'), 'walden');
    var myChart2 = echarts.init(document.getElementById('serviceMonitoring'), 'walden');
    var myChart3 = echarts.init(document.getElementById('serviceAccessLine'), 'walden');

    option = {
        title: {
            text: x.year + '月份',
            left: 20
        },
        tooltip: {
            trigger: 'axis',
            formatter: function (params, ticket, callback) {
                var showHtm = x.year + '-' + params[0].axisValueLabel + "的使用是" + params[0].data + '次';
                return showHtm
            }
        },
        xAxis: {
            type: 'category',
            data: x.data,
            boundaryGap: false,
            name:'日'
        },
        yAxis: {
            type: 'value',
            scale: true,
            boundaryGap: false,
            name:'次数'
        },
        series: [{
            data: dashboardData.PtSsFw,
            type: 'line',
            smooth: true
        }]
    }
    option1 = {
        tooltip: {
            formatter: "{a}{b} : {c}"
        },
        series: [{
                type: 'gauge',
                detail: {
                    formatter: '{value}'
                }, //仪表盘显示数据
                axisLine: { //仪表盘轴线样式
                    lineStyle: {
                        width: 10
                    }
                },
                splitLine: { //分割线样式
                    length: 10
                },
                data: [{
                    value: dashboardData.userCount,
                    name: '在线用户'
                }],
            }

        ]
    }
    option2 = {
        tooltip: {
            trigger: 'item'
        },
        legend:{
            bottom:"5%",
            icon:'circle',  // 图例形状 
            data: arr // 这块必须得加name属性，不然图例出不来
        },
        series: [{
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            label: {
                show: false,
                position: 'center'
            },
            emphasis: {
                label: {
                    show: true,
                    fontSize: '40',
                    fontWeight: 'bold'
                }
            },
            labelLine: {
                show: false
            },
            data: arr1
        }]
    };
    option3 = {
        tooltip: {
            trigger: 'axis',
        },
        legend:{
            icon:'circle',  // 图例形状 
            data: ['数据访问','专题服务','通用服务'] // 这块必须得加name属性，不然图例出不来
        },
        xAxis: {
            type: 'category',
            data: timer,
            boundaryGap: false,
            name:'月份'
        },
        yAxis: {
            type: 'value',
            scale: true,
            boundaryGap: false,
            name:'次数'
        },
        series: [{
            name:'数据访问',
            data: dashboardData.dateServicesCount,
            type: 'line',
            smooth: true
        },{
            name:'专题服务',
            data: dashboardData.thematicServicesCount,
            type: 'line',
            smooth: true
        },{
            name:'通用服务',
            data: dashboardData.noThematicServicesCount,
            type: 'line',
            smooth: true
        }]
    }
    myChart.setOption(option)
    myChart1.setOption(option1)
    myChart2.setOption(option2)
    myChart3.setOption(option3) 
    window.onresize = function () {
        myChart.resize();
        myChart1.resize();
        myChart2.resize();
        myChart3.resize();
    }

}

function textFun() {
    /* 
    .contentTab 
    <div style="display: flex;justify-content: space-between;height: 30px;">
                        <div style="color: rgb (76, 76, 76);">用户名AA</div>
                        <div style="color: rgb(190, 190, 190);">XXX规划科</div>
                        <div style="color: rgb(217, 0, 27);font-weight: 200;">235</div>
                    </div>
    */
    var contentTabHtml = ''
    let top = dashboardData.userUsedTop 
    let arr = ['rgb(249, 249, 249)','#fff'] 
    top.map((item,index) => {
        let color
        if (index % 2 == 0) {
            color = arr[0]
        } else {
            color = arr[1]
        }
        contentTabHtml += `
            <div style="display: flex;justify-content: space-between;height: 30px;background:${color};align-items: center;">
                <div style="color: rgb (76, 76, 76);width: 30%;text-align: left;">${item.userNo}</div>
                <div style="color: rgb(190, 190, 190);width: 40%;text-align: center;">${item.deptName}</div>
                <div style="color: rgb(217, 0, 27);font-weight: 200;width: 30%;text-align: right;">${item.sum}</div>
            </div>
        `
    })
    $('.contentTab').html(contentTabHtml)

}

function saveFun () {
    let hotResources   = dashboardData.hotResources 
    let tbResources = dashboardData.top10NewTbresources  
    let arr = ['rgb(249, 249, 249)','#fff'] 
    let hotResourcesHtml = ''
    hotResources.map((item,index) => {
        let color
        if (index % 2 == 0) {
            color = arr[0]
        } else {
            color = arr[1]
        }
        hotResourcesHtml += `
            <div class="fuDiv" style="background:${color};">
                <div>
                    <div style="color: rgb(51, 51, 51);">${item.layerName}</div>
                </div>
                <div style="color:rgb(217, 0, 27);">${item.sum}</div>
            </div>
        `
    })
    $('#textList1_div').html(hotResourcesHtml)

    let tbResourcesHtml = ''
    tbResources.map((item,index) => {
        let color
        if (index % 2 == 0) {
            color = arr[0]
        } else {
            color = arr[1]
        }  
        let time = new Date(item.savedate).toISOString().replace("T", " ").replace(".000Z", ""); 
        tbResourcesHtml += `
            <div class="fuDiv" style="background:${color};">
                <div style="color: rgb(51, 51, 51);">${item.name}</div>
                <div style="color: rgb(170, 170, 170);">${time}</div>
            </div>
        `
    })
    $('#textList2_div').html(tbResourcesHtml)
}

/*
http://localhost:8889/sw/resource/serviceMonitoring
平台运行时间  runTimes
平台访问量 platformVisits
注册用户 registerUserCounts
注册机构 deptCounts
服务总数 resourceCounts
异常服务 exceptionResource 
平台实时访问情况 PtSsFw
在线用户  userCount
用户访问次数排名Top10 userUsedTop type : 1 7天  2 两周 3 一个月  
服务监控 resourceBts  1值 数据服务个数 2 专题服务个数 3 通用服务个数 
服务访问情况    1 dateServicesCount 数据访问个数 2 thematicServicesCount 专题服务 3 noThematicServicesCount 通用服务  第一个数代表的一月份
热门服务 hotResources  
最新服务 top10NewTbresources
*/